﻿/***************************************************************************/
/// <summary>
///  <title>SLIC BaseController</title>
///  <description>BaseController for different format redirection</description>
///  <copyRight>Copyright (c) 2010</copyRight>
///  <company>IronOne Technologies (Pvt)Ltd</company>
///  <createdOn>2011-08-01</createdOn>
///  <author></author>
///  <modification>
///     <modifiedBy></modifiedBy>
///      <modifiedDate></modifiedDate>
///     <description></description>
///  </modification>
///
/// </summary>
/***************************************************************************/

using System;
using System.Web.Mvc;
using System.Web.Routing;

#region SLICReferences

using SLIC.Models.Auth;
using SLIC.Models.Enums;
//using SLIC.Models.Entity;

#endregion SLICReferences

#region ThirdPartyReferences
using log4net;
#endregion ThirdPartyReferences

namespace SLIC.Controllers
{    
    public class BaseController : Controller
    {
        protected static readonly ILog log = LogManager.GetLogger("root");

        ///OnAuthorization event override
        ///<returns>
        ///true if the role has permission for the invoked action
        ///if false goes to NotAuthorized action
        ///</returns>       
        ///<exception cref="">
        ///
        /// </exception>
        /// <remarks></remarks>
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",On Authorization," + User.Identity.Name);
                string action = filterContext.ActionDescriptor.ActionName;
                string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                string fmt = GetFormat();

                if (action.Equals("LogOn")) return;
                if (action.Equals("LogOff")) return;
                if (action.Equals("NotAuthorized")) return;
                if (action.Equals("Error")) return;
                if (action.Equals("SearchByVehicleNo")) return;

                bool authorized = RoleAuthorizationService.IsAuthorized(action + "_" + fmt);

                if (authorized)
                {
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",On Authorization," + User.Identity.Name);
                    return;
                }

                else
                {
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",On Authorization," + User.Identity.Name);
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "LogOn", action = "NotAuthorized", fmt }));
                }
            }
            catch (Exception e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",On Authorization," + User.Identity.Name);
            }
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",On Exception," + User.Identity.Name + "," + filterContext.Exception);
            //base.OnException(filterContext);
            ModelState.AddModelError("err", new GenException(132, filterContext.Exception.Message));
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Base", action = "Error" }));
        }

        ///GetFormatView Action Method
        ///<param name="pageUrl">Location of the view</param>
        ///<param name="model">model</param>
        ///<returns>
        ///Directs to the required view
        ///</returns>       
        ///<exception cref="">
        ///
        /// </exception>
        /// <remarks></remarks>
        public ActionResult GetFormatView(string pageUrl, object model)
        {
            return View("~/Views/" + GetFormat() + "/" + pageUrl, model);
        }

        public ActionResult ErrorView()
        {
            return GetFormatView("Account/Error.aspx");
        }


        ///GetFormatView Action Method
        ///<param name="pageUrl">Location of the view</param>
        ///<returns>
        ///Directs to the required view
        ///</returns>       
        ///<exception cref="">
        ///
        /// </exception>
        /// <remarks>GetFormatView without a model param</remarks>
        public ActionResult GetFormatView(string pageUrl)
        {
            return GetFormatView(pageUrl, null);
        }


        ///GetFormat return method
        ///<param name="catname">category name</param>
        ///<param name="meetingId">meeting Id</param>
        ///<returns>
        ///Gets fmt value from URL and returns it in uppercase
        ///</returns>       
        ///<exception cref="">
        ///
        /// </exception>
        /// <remarks></remarks>
        public String GetFormat()
        {
            String fmt = "HTML";

            fmt = Request.Params.Get("fmt");

            if (fmt == null)
            {
                if (Session["fmt"] != null)
                {
                    fmt = Session["fmt"].ToString();
                }
                else
                {
                    fmt = "HTML";
                }
            }
            return fmt.ToUpper();
        }


        ///GetLoggedUserId action method
        ///<returns>
        ///CustomUserId of the logged user
        ///</returns>       
        ///<exception cref="">
        ///Query failed
        /// </exception>
        /// <remarks></remarks>
        /*  public int GetLoggedUserId()
          {
              log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Logged User Id," + User.Identity.Name );
            
              if (!User.Identity.IsAuthenticated) 
              {
                  log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Logged User Id," + User.Identity.Name);
                  return 0; 
              }

              if (Session["UserId"] == null)
              {
                  try
                  {
                      //using (NTBBoardApprovalEntities ntb = new NTBBoardApprovalEntities())
                      //{
                      //    // MembershipUser muser = Membership.GetUser();
                      //    // if (muser!=null)
                      //    // {
                      //    IQueryable<int> x = from us in ntb.aspnet_Users
                      //                        where us.UserName == User.Identity.Name
                      //                        select (us.Users.FirstOrDefault().CustomUserId);

                      //    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Logged User Id," + User.Identity.Name);
                      //    return x.FirstOrDefault();                        
                      //    // } 
                      //}
                  }
                  catch (Exception e)
                  {
                      log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Logged User Id," + User.Identity.Name);
                      throw;
                  }
              }
              else
              {
                  log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",GetLoggedUserId," + User.Identity.Name + ",Session[UserId] != null" + "\n");
                  return int.Parse(Session["UserId"].ToString());
              }

          }*/
    }
}